package com.magold.modifier;

import org.andengine.util.modifier.BaseDurationModifier;
import org.andengine.util.modifier.IModifier;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;

public class SpeedScaleModifier extends BaseDurationModifier<Body> {
	private float mScale;
	private Vector2 mRealLinearVelocity;
	private float mRealAngularVelocity;
	
	public SpeedScaleModifier(float pScale, float pDuration) {
		this(pScale, pDuration, null);
	}
	
	public SpeedScaleModifier(float pScale, float pDuration, IModifierListener<Body> pModifierListener) {
		super(pDuration, pModifierListener);
		
		mScale = pScale;
	}

	@Override
	protected void onManagedUpdate(float pSecondsElapsed, Body pBody) {
		Vector2 currentLV = pBody.getLinearVelocity();
		Vector2 delta = currentLV.sub(mRealLinearVelocity.x*mScale, mRealLinearVelocity.y*mScale);
		mRealLinearVelocity.add(delta);

		float currentAV = pBody.getAngularVelocity();
		float dv = currentAV - mRealAngularVelocity*mScale;
		mRealAngularVelocity += dv;
				
		pBody.setLinearVelocity(mRealLinearVelocity.x*mScale, mRealLinearVelocity.y*mScale);
		pBody.setAngularVelocity(mRealAngularVelocity*mScale);
	}

	@Override
	protected void onManagedInitialize(Body pBody) {
		mRealLinearVelocity = new Vector2(pBody.getLinearVelocity());
		mRealAngularVelocity = pBody.getAngularVelocity();
		pBody.setLinearVelocity(mRealLinearVelocity.x*mScale, mRealLinearVelocity.y*mScale);
		pBody.setAngularVelocity(mRealAngularVelocity*mScale);
	}

	@Override
	public IModifier<Body> deepCopy() throws IModifier.DeepCopyNotSupportedException {
		return new SpeedScaleModifier(mScale, mDuration);
	}

	@Override
	public void reset() {
		mRealLinearVelocity = null;
		mRealAngularVelocity = 0;
		super.reset();
	}
}
